//
//  ViewController.m
//  04-掌握-GCD定时器
//
//  Created by J on 16/1/31.
//  Copyright © 2016年 J. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property(nonatomic,strong)dispatch_source_t timer;//dispatch_source_t就是一个类 自带星号
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    
}

int count = 0;
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    NSLog(@"touchesBegan");

    dispatch_time_t when = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0*NSEC_PER_SEC));
    dispatch_after(dispatch_time(when, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
    });
    //创建队列
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    
    
    //创建一个定时器
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    self.timer = timer;//强引用
    //    NSLog(@"%@",timer);// dispatch_source_t本质还是一个OC对象
    
    //比当前时间晚3s
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, 3.0*NSEC_PER_SEC);//合适开始执行第一个任务
    uint64_t interval = 2.0* NSEC_PER_SEC;//多久执行下一个任务
    //设置定时器各种属性(开始时间,每隔多长时间执行一次)
    
    dispatch_source_set_timer(timer, start, interval, 0);
    //设置回调
    dispatch_source_set_event_handler(timer, ^{
        
        NSLog(@"----");
        count ++;
        if (count==4) {
            dispatch_cancel(self.timer);//取消定时器
            self.timer = nil;
        }
    });
    //启动定时器
    dispatch_resume(timer);
    
//    dispatch_release(self.timer);
}

@end
